package com.himore.api.web.controller.modules;

import java.text.SimpleDateFormat;
import java.util.*;

import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.enums.SignRewardEnum;
import com.himore.api.common.enums.WeekInfoEnum;
import com.himore.api.common.utils.*;
import com.himore.api.system.service.ISysUserService;
import com.himore.api.web.enums.AwardsTypeEnum;
import com.himore.api.web.enums.SignTypeEnum;
import com.himore.api.web.enums.TaskIdEnum;
import com.himore.api.web.enums.WeekTaskTypeEnum;
import com.himore.api.web.model.*;
import com.himore.api.web.service.*;
import io.swagger.annotations.Api;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.himore.api.common.annotation.Log;
import com.himore.api.common.core.controller.BaseController;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.enums.BusinessType;

import com.himore.api.common.utils.poi.ExcelUtil;
import com.himore.api.common.core.page.TableDataInfo;

/**
 * 签到Controller
 * 
 * @author ruoyi
 * @date 2021-01-21
 */
@Api(tags = "签到信息管理")
@RestController
@RequestMapping("/system/record")
public class TSignRecordController extends BaseController
{
    @Autowired
    private ITSignRecordService tSignRecordService;

    @Autowired
    private ITWeekTaskInfoService tWeekTaskInfoService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ITTaskCompleteInfoService tTaskCompleteInfoService;
    @Autowired
    private ITSysTaskService tSysTaskService;

    @Autowired
    private ITSelectedAwardsService tSelectedAwardsService;

    /**
     * 获取签到详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tSignRecordService.selectTSignRecordById(id));
    }

    /**
     * 新增签到
     */
    @Log(title = "签到", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody TSignRecord tSignRecord) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tSignRecord.setUserId(user.getUserId());
        if(null == tSignRecord.getSignDate()){
            tSignRecord.setSignDate(DateUtils.getNowDate());
        }
        SysUser currentUser = userService.selectUserById(user.getUserId());
        Map<String, Date> params = CommonUtils.getWeekDate();
        Date signBeginDate = params.get("mondayDate");
        Date signEndDate = params.get("sundayDate");
        Date fridayDate = params.get("fridayDate");
        fridayDate = DateUtils.addTimeTodate(fridayDate,1);
        signEndDate = DateUtils.addTimeTodate(signEndDate,1);
        TSignRecord signRecord = new TSignRecord();
        signRecord.setUserId(user.getUserId());
        signRecord.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
        signRecord.setSigndateEnd(DateUtils.getYYYYMMDDDate(fridayDate));
        //在没有签到本次之前，查询出来已经签到的天数
        int preSignDays = tSignRecordService.selectSignDays(signRecord);
        //进行签到
        tSignRecordService.insertTSignRecord(tSignRecord);
        //在没有签到本次之前，查询出来已经签到的天数
        int afterSignDays = tSignRecordService.selectSignDays(signRecord);
        //签到获取的积分
        int  score = 0;
        //签到获取的补签卡
        //int  replenishSign=0;
        //是否需要更新积分 的标志
        boolean updateFlag = false;
        //如果是补签到
        if(SignTypeEnum.REPLENISHSIGN.getValue() == tSignRecord.getRecordType()){
            if(null== currentUser.getReplenishSign() ||  currentUser.getReplenishSign()<=0){
                return AjaxResult.error(ErrorCodeUtil.E_231,"您的补签到次数不足，不能补签到！");
            }
            //消耗补签次数
            SysUser u = new SysUser();
            u.setUserId(user.getUserId());
            u.setReplenishSign(-1);
            userService.updateScoreOrDrawInfo(u);
            //判断7天
            Calendar cal = Calendar.getInstance();
            TSignRecord signReco = new TSignRecord();
            signReco.setUserId(user.getUserId());
            signReco.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
            signReco.setSigndateEnd(DateUtils.getYYYYMMDDDate(signEndDate));
            //查询出来已经签到的天数
            int alreadySignDays = tSignRecordService.selectSignDays(signReco);
            if(alreadySignDays == 7){
                //根据任务的属性 就在我的奖品中生成一条数据
                TSelectedAwards tSelectedAwards = new TSelectedAwards();
                tSelectedAwards.setAwardId(SignRewardEnum.MONEY.getValue());
                tSelectedAwards.setAwardName(SignRewardEnum.MONEY.getName());
                tSelectedAwards.setAmount(5);
                tSelectedAwards.setUserId(user.getUserId());
                tSelectedAwards.setAwardType(AwardsTypeEnum.SIGN.getValue());
                tSelectedAwardsService.insertTSelectedAwards(tSelectedAwards);
            }
            if (preSignDays==4 && afterSignDays ==5){
                //根据任务的属性 就在我的奖品中生成一条数据
                TSelectedAwards tSelectedAwards = new TSelectedAwards();
                tSelectedAwards.setAwardId(SignRewardEnum.SCORE.getValue());
                tSelectedAwards.setAwardName(SignRewardEnum.SCORE.getName());
                tSelectedAwards.setAmount(5);
                tSelectedAwards.setUserId(user.getUserId());
                tSelectedAwards.setAwardType(AwardsTypeEnum.SIGN.getValue());
                tSelectedAwardsService.insertTSelectedAwards(tSelectedAwards);
                score += 5;
                updateFlag = true;
            }
        }else{
            //如果是正常签到则 通过判断 奖品id来
            if(null!= tSignRecord.getAwardId()){
                TWeekTaskInfo tWeekTaskInfo = tWeekTaskInfoService.selectTWeekTaskInfoById(tSignRecord.getAwardId());
                if(null!= tSignRecord.getSignDays() && tSignRecord.getSignDays()==tWeekTaskInfo.getDay()-1){
                    //根据任务的属性 就在我的奖品中生成一条数据
                    TSelectedAwards tSelectedAwards = new TSelectedAwards();
                    tSelectedAwards.setAwardId(tWeekTaskInfo.getTaskId());
                    tSelectedAwards.setAwardName(tWeekTaskInfo.getTaskName());
                    tSelectedAwards.setAmount(tWeekTaskInfo.getAmount());
                    tSelectedAwards.setUserId(user.getUserId());
                    tSelectedAwards.setAwardType(AwardsTypeEnum.SIGN.getValue());
                    tSelectedAwardsService.insertTSelectedAwards(tSelectedAwards);
                    if(WeekTaskTypeEnum.SCORE.getValue().equals(tWeekTaskInfo.getTaskType())){
                        score =score+tWeekTaskInfo.getAmount();
                    }
                    updateFlag = true;
                }
            }
        }
        //完成签到周任务的的积分的操作 增加相应的积分和红包
        try {
            //更新积分和补签到
            if(updateFlag){
                SysUser uss = new SysUser();
                uss.setUserId(user.getUserId());
                uss.setScore(score);
                //uss.setReplenishSign(replenishSign);
                userService.updateScoreOrDrawInfo(uss);
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(ErrorCodeUtil.E_500,"更新用户积分异常，请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 修改签到
     */
    @Log(title = "签到信息修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSignRecord tSignRecord)
    {
        return toAjax(tSignRecordService.updateTSignRecord(tSignRecord));
    }

    /**
     * 删除签到
     */
    @Log(title = "签到删除", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tSignRecordService.deleteTSignRecordByIds(ids));
    }


    /**
     * 查询签到列表
     */
    @GetMapping("/signList")
    public AjaxResult getSignList(TSignRecord tSignRecord) {
        SysUser sysUser =SecurityUtils.getLoginUser().getUser();
        SimpleDateFormat sdf  =new SimpleDateFormat(DateUtils.YYYY_MM_DD);
        Map<String, Date> params = CommonUtils.getWeekDate();
        Date signBeginDate = params.get("mondayDate");
        Date signEndDate = params.get("sundayDate");
        signEndDate = DateUtils.addTimeTodate(signEndDate,1);
        tSignRecord.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
        tSignRecord.setSigndateEnd(DateUtils.getYYYYMMDDDate(signEndDate));
        tSignRecord.setUserId(sysUser.getUserId());
        List<SignRecordVO> list = tSignRecordService.selectTSignRecordList(tSignRecord);

        List<SignRecordVO> signRecordVOS = new ArrayList<SignRecordVO>();
        for(int i=0;i<7;i++){
            SignRecordVO vo = new  SignRecordVO();
            String dateValue = sdf.format(DateUtils.addTimeTodate(signBeginDate,i));
            vo.setDateValue(dateValue);
            vo.setWeek(transferWeekInfo((i+1)+""));
            vo.setExists(checkIfExists(list,dateValue));
            vo= addWeekTask(vo,i+1);
            signRecordVOS.add(vo);
        }
        return AjaxResult.success(signRecordVOS);
    }

    public  SignRecordVO addWeekTask(SignRecordVO vo,int week){
        List<TWeekTaskInfo> tWeekTaskInfos = tWeekTaskInfoService.selectTWeekTaskInfoList(new TWeekTaskInfo());
        if(null!=tWeekTaskInfos && tWeekTaskInfos.size()>0){
            for(TWeekTaskInfo tWeekTaskInfo :tWeekTaskInfos){
                if(tWeekTaskInfo.getDay()== week){
                    vo.setExistsTask(true);
                    vo.setTaskId(tWeekTaskInfo.getTaskId());
                    vo.setTaskName(tWeekTaskInfo.getTaskName());
                    return vo;
                }
            }
        }
        vo.setExistsTask(false);
        vo.setTaskId(null);
        vo.setTaskName(null);
        return vo;
    }

    public  static boolean checkIfExists(List<SignRecordVO> list, String dateValue){
        for(SignRecordVO signRecordVO :list){
            if(signRecordVO.getFullDate().equals(dateValue)){
                return true;
            }
        }
        return false;
    }

    public String transferWeekInfo(String  week){

        if(WeekInfoEnum.MON.getValue().equals(week)){
            return  WeekInfoEnum.MON.getName();
            
        }
        if(WeekInfoEnum.TUE.getValue().equals(week)){
            return  WeekInfoEnum.TUE.getName();
            
        }
        if(WeekInfoEnum.WED.getValue().equals(week)){
            return  WeekInfoEnum.WED.getName();
            
        }
        if(WeekInfoEnum.THU.getValue().equals(week)){
            return  WeekInfoEnum.THU.getName();
            
        }
        if(WeekInfoEnum.FRI.getValue().equals(week)){
            return  WeekInfoEnum.FRI.getName();
            
        }
        if("7".equals(week)){
            return WeekInfoEnum.SUN.getName();
        }
        if(WeekInfoEnum.SAT.getValue().equals(week)){
            return  WeekInfoEnum.SAT.getName();
            
        }else{
            return  "";
        }
    }

    @GetMapping(value = "/getExternalInfo")
    public AjaxResult getUserInfo()
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Map<String, Date> params = CommonUtils.getWeekDate();
        Date signBeginDate = params.get("mondayDate");
        Date signEndDate = params.get("sundayDate");
        signEndDate = DateUtils.addTimeTodate(signEndDate,1);
        TSignRecord tSignRecord = new TSignRecord();
        //获取当前用户的最新信息
        SysUser currentUser =userService.selectUserById(sysUser.getUserId());
        tSignRecord.setUserId(sysUser.getUserId());
        tSignRecord.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
        tSignRecord.setSigndateEnd(DateUtils.getYYYYMMDDDate(signEndDate));
        HashMap result = new HashMap();
        int percent =tSignRecordService.selectSignPercent(tSignRecord);
        int  myPercent = tSignRecordService.selectSignCount(tSignRecord);
        if(0==myPercent){
            result.put("percent",0.01);
        }else {
            result.put("percent",percent);
        }
        result.put("score",currentUser.getScore());
        result.put("replenishSign",currentUser.getReplenishSign());
        return AjaxResult.success(result);
    }



}
